In [1]:
%matplotlib inline
from ggplot import *

Annotating Plots

As good as the ggplot defaults are, at some point you're going to want to customize and add information to your charts. Below you'll find some references for how to add labels, titles, and other info to your plots.

Axis Labels


In [2]:
ggplot(mtcars, aes(x='mpg')) + geom_histogram() + xlab("This is my X Label")


Out[2]:
<ggplot: (284494289)>

In [3]:
ggplot(mtcars, aes(x='mpg')) + geom_histogram() + xlab("This is my X\nIs on Multiple Lines")


Out[3]:
<ggplot: (285344633)>

In [4]:
ggplot(mtcars, aes(x='mpg')) + geom_histogram() + xlab("Miles per Gallon") + ylab("# of Cars")


Out[4]:
<ggplot: (285375649)>

Titles


In [5]:
ggplot(mtcars, aes(x='mpg')) + geom_histogram() + ggtitle("This is my Title")


Out[5]:
<ggplot: (285229585)>

In [6]:
ggplot(mtcars, aes(x='mpg')) + geom_histogram() + ggtitle("This is my Title\nOn Two Lines")


Out[6]:
<ggplot: (285649417)>

Custom Axis Values


In [7]:
ggplot(diamonds, aes(x='carat', y='price')) + geom_point() + xlim(0, 4)


Out[7]:
<ggplot: (285759001)>

In [8]:
ggplot(diamonds, aes(x='carat', y='price')) + geom_point() + xlim(0, 4) + ylim(0, 20000)


Out[8]:
<ggplot: (285895321)>

In [9]:
ggplot(diamonds, aes(x='carat', y='price')) + \
    geom_point() + \
    xlim(0, 4) + \
    ylim(0, 20000) + \
    scale_x_continuous("Carat", breaks=[0, 2, 4])


Out[9]:
<ggplot: (290332957)>

In [10]:
ggplot(diamonds, aes(x='carat', y='price')) + \
    geom_point() + \
    xlim(0, 4) + \
    ylim(0, 20000) + \
    scale_x_continuous("Carat", breaks=[0, 2, 4], labels=["Small", "Medium", "Large"])


Out[10]:
<ggplot: (285229721)>

In [11]:
ggplot(diamonds, aes(x='carat', y='price')) + \
    geom_point() + \
    xlim(0, 4) + \
    ylim(0, 20000) + \
    scale_x_continuous("Carat (200mg)", breaks=[0, 2, 4], labels=["Small", "Medium", "Large"]) + \
    scale_y_continuous("Price ($)", breaks=[0, 10000, 20000], labels=["\$", "\$$", "\$\$$"])


Out[11]:
<ggplot: (290734197)>

In [12]:
ggplot(diamonds, aes(x='carat', y='price')) + \
    geom_point() + \
    geom_hline(y=2500, color='red') + \
    xlim(0, 4) + \
    ylim(0, 20000) + \
    scale_x_continuous("Carat (200mg)", breaks=[0, 2, 4], labels=["Small", "Medium", "Large"]) + \
    scale_y_continuous("Price", breaks=[0, 2500, 10000, 20000], labels=["", "You better be above here", "\$$", "\$\$$"])


Out[12]:
<ggplot: (291524441)>

In [13]:
ggplot(diamonds, aes(x='cut')) + \
    geom_bar()


Out[13]:
<ggplot: (290843349)>

In [14]:
ggplot(diamonds, aes(x='cut')) + \
    geom_bar() + \
    scale_x_discrete("Diamond Cut")


Out[14]:
<ggplot: (292419293)>

In [15]:
ggplot(diamonds, aes(x='cut')) + \
    geom_bar() + \
    scale_x_discrete("Diamond Cut", labels=["i", "p", "vg", "g", "f"])


Out[15]:
<ggplot: (290365305)>

In [16]:
ggplot(diamonds, aes(x='cut')) + \
    geom_bar() + \
    scale_x_discrete("Diamond Cut", labels=["*", "**", "***", "****", "*****"])


Out[16]:
<ggplot: (294616993)>

In [ ]: